using UnityEngine;

namespace Tools
{
    public class MonoSingletonProvider<T> : MonoBehaviour
        where T : Component
    {
        private static T _inst;

        public static T inst
        {
            get
            {
                if (_inst == null)
                {
                    var go = new GameObject();
                    _inst = (T) go.AddComponent(typeof(T));
                    go.name = "---<Singleton>---" + typeof(T).Name;
                    go.hideFlags = HideFlags.DontSave;
                    DontDestroyOnLoad(go);
                    var st = _inst as MonoSingletonProvider<T>;
                    st?.InstanceInit();
                }
                return _inst;
            }
        }

        public static bool hasInstance => _inst != null;

        /// <summary>
        /// 第一次创建实例的调用代码
        /// </summary>
        protected virtual void InstanceInit()
        {
        }


        protected virtual void Awake()
        {
        }

        protected virtual void Start()
        {
        }

        protected virtual void OnDestroy()
        {
            _inst = null;
            Resources.UnloadUnusedAssets();
        }

        protected virtual void OnApplicationQuit()
        {
            DestroyInst();
        }

        protected virtual void DestroyInst()
        {
            Destroy(gameObject);
        }
    }
}